package com.itheima.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.itheim.client.pojo.Order;
import com.itheim.client.pojo.OrderDetail;
import com.itheim.client.pojo.ShoppingCart;
import com.itheim.client.pojo.User;
import com.itheim.client.vo.AddressVo;
import com.itheim.client.vo.OrderDetailVo;
import com.itheim.client.vo.OrderVo;
import com.itheima.admin.pojo.Page;
import com.itheima.client.mapper.COrderMapper;
import com.itheima.client.mapper.OrderDetailMapper;
import com.itheima.common.R;
import com.itheima.service.COrderService;
import com.itheima.util.PageUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Author longbosheng
 * @Date 2022/6/22 9:05
 * @PackageName:com.itheima.service.Impl
 * @ClassName: OrderServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class COrderServiceImpl implements COrderService {
    @Autowired
    private COrderMapper corderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 添加订单
     *
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrder(@RequestBody Order order) {
//        按地址id查询地址详细信息
        AddressVo addressVo = corderMapper.selectAddressById(order);
        //获取购物车信息
        List<ShoppingCart> list = corderMapper.ShoppingCartInfo(order);
//        获取下单用户信息
        User user = corderMapper.selectOrderUser(order.getUserId());
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        //先自动生成id
        String id = IdUtil.getSnowflakeNextIdStr();
        //自动生成固定格式的订单号
        String number = "RG" + System.currentTimeMillis();
        //将信息添加到订单表
        order.setId(id);
        order.setNumber(number);
        order.setUserName(user.getName());
        order.setPhone(addressVo.getPhone());
        order.setAddress(addressVo.getDetail());
        order.setConsignee(addressVo.getConsignee());
        order.setStatus(2);
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());

        //获取总金额
        BigDecimal amount = new BigDecimal(0.00);
        //将查询到的信息添加到订单详情表
        for (ShoppingCart shoppingCart : list) {
            System.out.println("查询出来购物车的信息：" + shoppingCart);
            OrderDetail orderDetail = new OrderDetail();
            if (shoppingCart == null) {
                continue;
            }
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(order.getId());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            //计算该商品的总金额
            int money = shoppingCart.getNumber();
            BigDecimal amount1 = shoppingCart.getAmount();
            amount = amount1.multiply(new BigDecimal(money)).add(amount);
            orderDetailMapper.insert(orderDetail);
        }
        //获取总金额
        order.setAmount(amount);
        //添加订单表
        int insert = corderMapper.insert(order);
        //判断是否添加成功
        if (insert > 0) {
            System.out.println("用户id" + order.getUserId());
            //生成订单成功，清空购物车
            return corderMapper.clearShoppingCart(order.getUserId()) ? true : false;
        }
        return false;
    }

    /**
     * 分页查询订单列表
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public R orderList(int page, int pageSize, String userId) {
        int offset = PageUitl.getOffset(page, pageSize);
        int total = corderMapper.gettotal(userId);
        List<OrderVo> orderVos = corderMapper.orderList(offset, pageSize, userId);
        if (CollectionUtils.isEmpty(orderVos)) {
            return R.success("到底了");
        }
        //将订单信息加入到列表中
        int i = 0;
        for (OrderVo orderVo : orderVos) {
            List<OrderDetailVo> orderDetailVos = corderMapper.detailList(orderVo.getId());
            if (CollectionUtils.isEmpty(orderVos)) {
                continue;
            }
            orderVo.setOrderDetails(orderDetailVos);
            i++;
            /*得到总页数*/
            int pageCount =  (total-1)/pageSize+1;

            if (i == orderVos.size()) {
                Page page1 = new Page();
                page1.setCurrent(page);
                page1.setSize(pageSize);
                page1.setTotal(total);
                page1.setRecords(orderVos);
                page1.setPages(pageCount);
                return R.success(page1);
            }
        }
        return R.error("添加详细订单异常");
    }
}
